<?php
/**
 * Created by PhpStorm.
 * User: chang
 * Date: 2019/3/22
 * Time: 15:09
 */

namespace App\Http\Model;

use App\Http\Services\FinanceServices;
use App\Http\Services\MaximumGoldRoomServices;
use App\Http\Services\BoardExtendServices;
use App\Http\Services\RoomMsgServices;
use App\Lib\Publisher;
use App\Lib\Snowflake\SnowflakeGenerator;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class FinanceRoomWealth extends Base
{
    public $table = "finance_room_wealth_total";
    public $timestamps = false;
    protected $dateFormat = 'U';
    protected $roomStreamTable = 'finance_room_wealth_stream';

    // 房间流水月统计
    protected $financeRoomWalletMonth = 'finance_room_wealth_month';
    protected $roomTable = 'room';
    protected $beforeFinanceLogTable = 'finance_before_kk_log';


    protected $attributes = [
        'mark' => 0
    ];
    # 房间内 用户送礼榜 富豪榜
    private $redis_charts_room_user_wealth_day = "FINANCE:CHARTS:ROOM:USER:WEALTH:DAY:"; // FINANCE:CHARTS:ROOM:USER:WEALTH:DAY:{room_id}-2018-11-22
    private $redis_charts_room_user_wealth_yestorday = "FINANCE:CHARTS:ROOM:USER:WEALTH:YESTORDAY:";//FINANCE:CHARTS:ROOM:USER:WEALTH:YESTORDAY:{room_id}-2018-11-22
    private $redis_charts_room_user_wealth_lastweek = "FINANCE:CHARTS:ROOM:USER:WEALTH:LASTWEEK:";//FINANCE:CHARTS:ROOM:USER:WEALTH:LASTWEEK:{roomid}-2018-11-22|2018-11-22
    private $redis_charts_room_user_wealth_week = "FINANCE:CHARTS:ROOM:USER:WEALTH:WEEK:"; // FINANCE:CHARTS:ROOM:USER:WEALTH:DAY:{room_id}-2018-11-222018-11-20
    private $redis_charts_room_user_wealth_month = "FINANCE:CHARTS:ROOM:USER:WEALTH:MONTH:"; // FINANCE:CHARTS:ROOM:USER:WEALTH:DAY:{room_id}-2018-11
    private $redis_charts_room_user_wealth_all = "FINANCE:CHARTS:ROOM:USER:WEALTH:ALL:"; // FINANCE:CHARTS:ROOM:USER:WEALTH:ALL:{room_id}
    # 房间 财富榜
    private $redis_charts_room_wealth_day = "FINANCE:CHARTS:ROOM:WEALTH:DAY:"; // FINANCE:CHARTS:ROOM:WEALTH:DAY:2018-11-22
    private $redis_charts_room_wealth_week = "FINANCE:CHARTS:ROOM:WEALTH:WEEK:"; // FINANCE:CHARTS:ROOM:WEALTH:DAY:2018-11-222018-11-20
    private $redis_charts_room_wealth_month = "FINANCE:CHARTS:ROOM:WEALTH:MONTH:"; // FINANCE:CHARTS:ROOM:WEALTH:DAY:2018-11
    private $redis_charts_room_wealth_all = "FINANCE:CHARTS:ROOM:WEALTH:ALL"; // FINANCE:CHARTS:ROOM:WEALTH:ALL
    # 最多金房间 财富榜
    private $redis_charts_room_wealth_day_maximum_gold = "FINANCE:CHARTS:ROOM:WEALTH:DAY:MAXIMUM:GOLD:"; // FINANCE:CHARTS:ROOM:WEALTH:DAY:MAXIMUM:GOLD:2018-11-22
    private $redis_charts_room_wealth_week_maximum_gold = "FINANCE:CHARTS:ROOM:WEALTH:WEEK:MAXIMUM:GOLD:"; // FINANCE:CHARTS:ROOM:WEALTH:DAY:MAXIMUM:GOLD:2018-11-222018-11-20
    private $redis_charts_room_wealth_month_maximum_gold = "FINANCE:CHARTS:ROOM:WEALTH:MONTH:MAXIMUM:GOLD:"; // FINANCE:CHARTS:ROOM:WEALTH:DAY:MAXIMUM:GOLD:2018-11
    private $redis_charts_room_wealth_all_maximum_gold = "FINANCE:CHARTS:ROOM:WEALTH:ALL:MAXIMUM:GOLD"; // FINANCE:CHARTS:ROOM:WEALTH:ALL:MAXIMUM:GOLD
    # 房间送礼榜 财富榜
    private $redis_cache_finance_room_wallet = "CACHE:FINANCE:ROOM:WALLET";
    private $redis_cache_finance_room_wealth = "CACHE:FINANCE:ROOM:WEALTH:"; //CACHE:FINANCE:ROOM:WEALTH:20181101

    # 神豪的送礼积分榜(守护榜)
    public $redis_charts_room_vip_mvp_charm_day  = "FINANCE:CHARTS:ROOM:VIP:MVP:CHARM:DAY:%s:%s:%s"; // FINANCE:CHARTS:ROOM:VIP:MVP:DAY:{room_id}:{user_id}:{20220607}
    # 当前房间的神豪和守护uid
    private $redis_charts_room_vip_mvp_user_day   = "FINANCE:CHARTS:ROOM:VIP:MVP:USER:DAY:%s:%s"; // FINANCE:CHARTS:ROOM:VIP:MVP:DAY:{room_id}:{20220607}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
//        DB::connection()->enableQueryLog();
    }

    /**
     * @param int $room_id
     * @param int $total
     * @return bool
     * @throws \Throwable
     */
    public function add(int $room_id, int $total = 0){
        $model = new FinanceRoomWealth();
        $model->room_id = $room_id;
        $model->total = $total;
        $model->day = date('Y-m-d', $_SERVER['REQUEST_TIME']);
        return $model->saveOrFail();
    }

    /**
     * 累加
     * @param int $room_id
     * @param int $increment
     * @return mixed
     */
    public function incTotal(int $room_id, int $increment = 1){
        $day = date("Y-m-d");
        $res = DB::INSERT("INSERT INTO zb_{$this->table} (`room_id`,`day`,`total`) VALUE({$room_id}, '{$day}',{$increment}) ON DUPLICATE KEY UPDATE total=total+{$increment}");
        return $res;
    }

    /**
     * 自动结算上月
     * @aray $room_id
     * @return mixed
     */
    public function closeAnAccount(array $room_id){
        $curFirstDay = date('Y-m-01', strtotime('-1 month'));                          // 当前月第一天
        $curEndDay = date('Y-m-d', strtotime("{$curFirstDay} +1 month -1 day"));   // 当前月最后一天
       $res = $this->whereBetween('day',[$curFirstDay, $curEndDay])->whereIn('room_id',$room_id)->update(['mark' => 1]);
       return $res;
    }

//    public function getCloseAnAccount(array $room_id){
//        $curFirstDay = date('Y-m-01', strtotime('-1 month'));                          // 当前月第一天
//        $curEndDay = date('Y-m-d', strtotime("{$curFirstDay} +1 month -1 day"));   // 当前月最后一天
//        $res = DB::SELECT("SELECT SUM(`total`) AS total,`room_id` FROM `zb_{$this->table}` WHERE `room_id` IN('".implode(',',$room_id)."') AND `day` BETWEEN '{$curFirstDay}' AND '{$curEndDay}' AND `mark`=1 GROUP BY `room_id`");
//        return json_decode(json_encode($res),true);
//    }

    public function getCloseAnAccount(array $room_id){
        $curFirstDay = date('Y-m-01', strtotime('-1 month'));                          // 当前月第一天
        $curEndDay = date('Y-m-d', strtotime("{$curFirstDay} +1 month -1 day"));   // 当前月最后一天

        $result = [];
        FinanceRoomWealth::whereIn('room_id',$room_id)
            ->whereBetween('day',[$curFirstDay,$curEndDay])
            ->where(['mark' => 0])
            ->select(['room_id','total'])
            ->chunk(10000,function ($finance_room_wealth) use (&$result){
            foreach ($finance_room_wealth as $wealth) {
                if(!isset($result[$wealth->room_id])){
                    $result[$wealth->room_id] = $wealth->total;
                } else {
                    $result[$wealth->room_id] += $wealth->total;
                }
            }
        });
        return $result;
    }

    /**
     * 当月收益
     * @param int $room_id
     * @param string $date
     * @return mixed
     */
    public function getFinanceRoomWealthList(int $room_id, string $date){
        $currentFirstDay = date('Y-m-01', $date);                                                        // 当前月第一天
        $currentLastDay = date('Y-m-d', strtotime("$currentFirstDay +1 month -1 day"));      // 当前月最后一天

        $res = DB::SELECT("SELECT UNIX_TIMESTAMP(`day`) AS day, total FROM `zb_{$this->table}` WHERE `room_id`={$room_id} AND `day` BETWEEN '{$currentFirstDay}' AND '{$currentLastDay}' ORDER BY `day` DESC");
        return json_decode(json_encode($res),true);
    }


    /**
     * 获取房间月份总流水
     * @param $roomId
     * @param int $prvMonth 0 当前月 1 前1个月 2 前2个月
     * @return int|mixed
     */
    public function getRoomWealthTotal($roomId, $prvMonth = 0)
    {
        $startDay = date('Y-m-01', strtotime("-$prvMonth month"));
        $endDay = date('Y-m-d', strtotime("$startDay +1 month -1 day"));
        $total = DB::table('finance_room_wealth_total')
            ->where('room_id', '=', $roomId)
            ->where('day', '>=', $startDay)
            ->where('day', '<=', $endDay)
            ->sum('total');
        if (empty($total)){
            return 0;
        }
        return $total;
    }


    /**
     * 获取所有房间流水
     * @param int $prvMonth
     * @return array|mixed
     */
    public function getRoomWealthArr($prvMonth = 0)
    {
        $startDay = date('Y-m-01', strtotime("-$prvMonth month"));
        $endDay = date('Y-m-d', strtotime("$startDay +1 month -1 day"));
        $result = DB::table('finance_room_wealth_total')
            ->where('day', '>=', $startDay)
            ->where('day', '<=', $endDay)
            ->groupBy('room_id')
            ->select('room_id',DB::raw('sum(total) as total'))
            ->get();
        if (empty($result)) {
            return [];
        }
        return $this->objToArray($result);
    }

    public function getRoomIdArr($month){
        $startDay = date('Y-m-01', strtotime($month));
        $endDay = date('Y-m-d', strtotime("$startDay +1 month -1 day"));
        echo "{$startDay}-{$endDay} \n";
        $result = DB::table('finance_room_wealth_total')
            ->where('day', '>=', $startDay)
            ->where('day', '<=', $endDay)
            ->select('room_id')
            ->distinct()
            ->get();
        if (empty($result)) {
            return [];
        }
        echo json_encode($result) . "\n";
        return $result;
    }



    /**
     * 获取房间的排行榜
     * @param $type
     * @param $index
     * @param $count
     * @return mixed
     */
    public function get_room_charts($type, $index, $count){
        $str_month = date("Ym");
        $str_day = date("Ymd");
        $first=1;
        $w=date('w',strtotime($str_day));
        $str_week_start=date('Ymd',strtotime("$str_day -".($w ? $w - $first : 6).' days'));
        $str_week_end=date('Ymd',strtotime("$str_week_start +6 days"));
        $room_day_key = $this->redis_charts_room_wealth_day .  $str_day;
        $room_week_key = $this->redis_charts_room_wealth_week .  $str_week_start . $str_week_end;
        $room_month_key = $this->redis_charts_room_wealth_month .  $str_month;
        $room_all_key = $this->redis_charts_room_wealth_all;


        $key = $room_day_key;

        if ($type == 1){
            $key = $room_day_key;
        }
        if ($type == 2){
            $key = $room_week_key;
        }
        if ($type == 3){
            $key = $room_month_key;
        }
        return Redis::zrevrange($key, $index, $index+$count-1, 'withscores');
    }

    /**
     * 获取房间的排行榜-最多金
     * @param $type
     * @param $index
     * @param $count
     * @return mixed
     */
    public function get_room_charts_maximum_gold($type, $index, $count)
    {
        $str_month = date("Ym");
        $str_day = date("Ymd");
        $first = 1;
        $w = date('w',strtotime($str_day));
        $str_week_start = date('Ymd',strtotime("$str_day -".($w ? $w - $first : 6).' days'));
        $str_week_end = date('Ymd',strtotime("$str_week_start +6 days"));
        $room_day_key = $this->redis_charts_room_wealth_day_maximum_gold .  $str_day;
        $room_week_key = $this->redis_charts_room_wealth_week_maximum_gold .  $str_week_start . $str_week_end;
        $room_month_key = $this->redis_charts_room_wealth_month_maximum_gold .  $str_month;
        $key = $room_day_key;
        if ($type == 1){
            $key = $room_day_key;
        }

        if ($type == 2){
            $key = $room_week_key;
        }

        if ($type == 3){
            $key = $room_month_key;
        }

        return Redis::zrevrange($key, $index, $index + $count - 1, 'withscores');
    }


    /**
     * 获取房间财富值排行榜
     * @param $type 1.天 2.周 -.月 3.总 4.昨日 5上周
     * @param $room_id
     * @param $index
     * @param $count
     * @return mixed
     */
    public function get_room_user_charts($type, $room_id, $index, $count){
        $str_day = date('Ymd');
        //周一
        $str_week_start = date("Ymd", strtotime('this week Monday'));
        //周日
        $str_week_end = date("Ymd", strtotime('this week Sunday'));
        //当日
        $room_user_day_key = $this->redis_charts_room_user_wealth_day . $room_id . $str_day;
        //本周
        $room_user_week_key = $this->redis_charts_room_user_wealth_week . $room_id . $str_week_start . $str_week_end;
        //昨日
        $yestorday = Carbon::yesterday()->toDateString();
        $room_user_yestorDay_key = $this->redis_charts_room_user_wealth_yestorday . $room_id .':'. $yestorday;
        //上周
        // 获取上周的开始日期（周一）
        $startOfLastWeek = Carbon::now()->subWeek()->startOfWeek()->toDateString();
        
        // 获取上周的结束日期（周日）
        $endOfLastWeek = Carbon::now()->subWeek()->endOfWeek()->toDateString();
        $room_user_lastweek_key = $this->redis_charts_room_user_wealth_lastweek . $room_id .':'. $startOfLastWeek.'|'. $endOfLastWeek;


        $key = $room_user_day_key;

        if ($type == 1){
            $key = $room_user_day_key;
        }elseif ($type == 2){
            $key = $room_user_week_key;
            $this->checkRoomWealthUserWeek($key,$room_id , $str_week_start , $str_week_end);
        }elseif($type == 4){
            $key = $room_user_yestorDay_key;
        }elseif($type == 5){
            $key = $room_user_lastweek_key;
        }
        return Redis::zrevrange($key, $index, $index+$count-1, 'withscores');
    }


    /**
     *  房间内-个人财富榜
     *  最多金房间\房间 财富榜
     *
     * @param $user_id int 送礼物的用户id
     * @param $from_user_id int 收礼物的用户id
     * @param $wealth_value
     * @param $room_id
     */
    public function inc_charts($user_id, $from_user_id,$wealth_value, $room_id){
        write_log("finance", "inc-wealth-".$room_id, [$user_id, $room_id, $wealth_value]);
        $str_month = date("Ym");
        $str_day = date("Ymd");
        $first=1;
        $w=date('w',strtotime($str_day));
        $str_week_start=date('Ymd',strtotime("$str_day -".($w ? $w - $first : 6).' days'));
        $str_week_end=date('Ymd',strtotime("$str_week_start +6 days"));
        
        //更新房间财富榜单第一名
        $this->updateRoomChampion($room_id ,$user_id,$from_user_id,$wealth_value);

        //更新房间神豪守护榜。守护榜是神豪送礼最多的那个人。
        $vip_mvp_key = sprintf($this->redis_charts_room_vip_mvp_charm_day, $room_id, $user_id, $str_day);
        Redis::zincrby($vip_mvp_key, $wealth_value, $from_user_id);
        if (Redis::TTL($vip_mvp_key) == -1) {
            Redis::EXPIRE($vip_mvp_key, 48 * 3600);
        }

        //房间内 个人财富榜
        $room_user_day_key = $this->redis_charts_room_user_wealth_day . $room_id . $str_day;
        $room_user_week_key = $this->redis_charts_room_user_wealth_week . $room_id . $str_week_start . $str_week_end;

        Redis::zincrby($room_user_day_key, $wealth_value, $user_id);// 房间内 用户送礼榜 天
//        write_log("finance", "inc-wealth-day".$room_id, [$user_id, $room_id, $wealth_value]);
        $this->checkRoomWealthUserWeek($room_user_week_key,$room_id , $str_week_start , $str_week_end);
        Redis::zincrby($room_user_week_key, $wealth_value, $user_id);// 房间内 用户送礼榜 天
        if(Redis::TTL($room_user_day_key) == -1){
            Redis::EXPIRE($room_user_day_key, 2 * 24 * 3600);
        }
        if(Redis::TTL($room_user_week_key) == -1){
            Redis::EXPIRE($room_user_week_key, 2 * 7 * 24 * 3600);
        }

        // 房间 财富榜
        $room_day_key = $this->redis_charts_room_wealth_day .  $str_day;
        $room_week_key = $this->redis_charts_room_wealth_week .  $str_week_start . $str_week_end;
        $room_month_key = $this->redis_charts_room_wealth_month .  $str_month;
        $room_all_key = $this->redis_charts_room_wealth_all;
        $maximumGoldRoomIds = (new MaximumGoldRoomServices())->getRoomIds();
        if ($room_id && $maximumGoldRoomIds && in_array($room_id, $maximumGoldRoomIds)) {// 最多金榜单
            $room_day_key = $this->redis_charts_room_wealth_day_maximum_gold .  $str_day;
            $room_week_key = $this->redis_charts_room_wealth_week_maximum_gold .  $str_week_start . $str_week_end;
            $room_month_key = $this->redis_charts_room_wealth_month_maximum_gold .  $str_month;
            $room_all_key = $this->redis_charts_room_wealth_all_maximum_gold;
        }

        Redis::zincrby($room_day_key, $wealth_value, $room_id);
        Redis::zincrby($room_week_key, $wealth_value, $room_id);
        Redis::zincrby($room_month_key, $wealth_value, $room_id);
        Redis::zincrby($room_all_key, $wealth_value, $room_id);

        Redis::EXPIRE($room_week_key, 2 * 31 * 24 * 3600);
        Redis::EXPIRE($room_week_key, 2 * 31 * 24 * 3600);
        Redis::EXPIRE($room_month_key, 2 * 31 * 24 * 3600);
    }


    /**
     * 获得房间财富值列表
     * @return mixed
     */
    public function get_rooms_wealth_tmp(){
        $time_tag =  date('Ymd', time());
        $data = Redis::HGETALL($this->redis_cache_finance_room_wealth . $time_tag);
        return $data;
    }

    /**
     * 获取单条房间财富值
     * @param $room_id
     * @return int
     */
    public function get_room_wealth_tmp($room_id){
        $time_tag =  date('Ymd', time());
        $data = Redis::HGET($this->redis_cache_finance_room_wealth . $time_tag, $room_id);
        if (empty($data)){
            return 0;
        }
        return intval($data);
    }

    /**
     * 更新财富值
     * @param $user_id
     * @param $from_user_id
     * @param $room_id
     * @param $wealth_type 0.礼物、1.守护、2.商品、3.背包礼物 4.夺宝 66.蜜屋 99.比心礼物
     * @param $room_wealth_value
     * @return bool
     * @throws \Throwable
     */
    public function inc($user_id, $from_user_id, $room_id, $wealth_type, $room_wealth_value, $is_certified, $TimedGoodsScore=0, $gift_stream_id=0){
        if ($room_id > 0){
            write_log("FinanceRoomWallet", "inc-room-wallet-" . $room_id, [$user_id, $from_user_id, $room_id, $wealth_type, $room_wealth_value, $is_certified]);
            DB::table("finance_room_wallet")
                ->where(['room_id'=>$room_id])
                ->increment('wealth_balance',$room_wealth_value,['change_timestamp'=> time()]);

            $trackId = SnowflakeGenerator::generateId('finance_room_wealth_stream');
            DB::table('finance_room_wealth_stream')->insert([
                'gift_stream_id' => $gift_stream_id,
                "track_id" => $trackId,
                'room_id' => $room_id,
                'user_id' => $user_id,
                'from_user_id' => $from_user_id,
                'wealth_type' => $wealth_type,
                'wealth_value' => $room_wealth_value,
                'create_timestamp' =>  time()
            ]);
            // 房间收益
            if ($is_certified == 1){
                $this->incTotal($room_id,$room_wealth_value);
            }

            $room_wealth_value += $TimedGoodsScore;// 比心礼物值追加到
            if ($room_wealth_value<=0){
                return true;
            }

            $time_tag =  date('Ymd', time());
            Redis::HINCRBY($this->redis_cache_finance_room_wealth . $time_tag, $room_id, intval($room_wealth_value));
            if(Redis::TTL($this->redis_cache_finance_room_wealth . $time_tag) == -1){
                Redis::EXPIRE($this->redis_cache_finance_room_wealth . $time_tag, 3600*48);
            }
            Redis::HDEL($this->redis_cache_finance_room_wallet, $room_id);
            $this->inc_charts($user_id, $from_user_id,$room_wealth_value, $room_id);
        }
        return true;
    }


    /**
     * 按月份查询房间总流水数据
     * */
    public function getWealthTotalData($startTime,$endTime){
        $this->table = 'finance_room_wealth_total';
        $data = DB::table($this->table)
            ->leftJoin($this->roomTable,$this->table.'.room_id','=',$this->roomTable.'.room_id')
            ->whereBetween('day', [$startTime, $endTime])
            ->select($this->table.'.id',$this->table.'.room_id',$this->roomTable.'.user_id', DB::raw('SUM(total) as total'))
            ->groupBy('room_id')
            ->get();
        return self::objToArray($data);
    }

    /**
     * 按月份查询房间月流水
     * */
    public function getWealthMonthData($condition,$single = false){
        $this->table = $this->financeRoomWalletMonth;
        $data = $this->getSingle($condition,['room_id','user_id','wealth','original','modify','month','type'],$single);
        return self::objToArray($data);
    }

    /**
     * 房间流水生成
     * */
    public function createWealthMonth($data){
        $this->table = $this->financeRoomWalletMonth;
        return $this->insertBatch($data);
    }

    /**
     * 房间流水更新
     * */
    public function updateWealthMonth($condition,$data){
        $this->table = $this->financeRoomWalletMonth;
        return $this->singleUpdate($condition,$data);
    }

    /*
     * 房间上月流水统计
     * */
    public function monthWealthToRoomId($id)
    {
        $where['id'] = $id;
        $res = DB::table($this->financeRoomWalletMonth)->where($where)->first();
        return $this->objToArray($res);
    }


    /*
     * 房间当日流水
     * @param arr $room_ids
     * */
    public function getRoomWealthToRoomIds($room_ids = [],$startDay,$endDay)
    {

        $res = DB::table($this->table)->whereIn('room_id',$room_ids)
            ->where('day', '>=', $startDay)
            ->where('day', '<=', $endDay)->get();
        return $this->objToArray($res);
    }


    /**
     * 获取流水详情
     * @param int $room_id
     * @param int $date
     * @param int $page
     * @param int $length
     * @return array
     */
    public function getStream(int $roomId, int $startTime, int $endTime, int $page, int $length){
        $offset = $page * $length;
        $res = DB::table('finance_room_wealth_stream')
            ->where('room_id', '=', $roomId)
            ->where('create_timestamp', '>=', $startTime)
            ->where('create_timestamp', '<=', $endTime)
            ->offset($offset)
            ->limit($length)
            ->get(['user_id', 'from_user_id', 'wealth_value as room_wealth_value', 'create_timestamp as change_time', 'create_timestamp as change_timestamp']);
        $res = $this->objToArray($res);
        return $res;
    }


    /**
     * 获取流水总值
     * @param int $roomId
     * @param int $startTime
     * @param int $endTime
     * @return mixed
     */
    public function getStreamTotal(int $roomId, int $startTime, int $endTime) {
        $total = DB::table('finance_room_wealth_stream')
            ->where('room_id', '=', $roomId)
            ->where('create_timestamp', '>=', $startTime)
            ->where('create_timestamp', '<=', $endTime)
            ->sum('wealth_value');
        return $total;
    }
    /**
     * 获取流水总值  同步排行榜使用
     * @param int $roomId
     * @param int $startTime
     * @param int $endTime
     * @return mixed
     */
    public function getStreamTotalV1(int $roomId, int $startTime, int $endTime) {
        $total = DB::table('finance_room_wealth_stream')
            ->where('room_id', '=', $roomId)
            ->where('create_timestamp', '>=', $startTime)
            ->where('create_timestamp', '<=', $endTime)
            ->sum('wealth_value');
        // 计算计时礼物积分
        $count = DB::table('finance_room_wealth_stream')
            ->where('room_id', '=', $roomId)
            ->where('wealth_type', '=', 99)
            ->where('create_timestamp', '>=', $startTime)
            ->where('create_timestamp', '<=', $endTime)
            ->count();
        if ($count> 0){
            // 当天 最多可兑换分数
            $todayMaxScore = (new BoardExtendServices()) -> calcTimedGiftScore($count);
            $total += $todayMaxScore;
        }

        return $total;
    }

    /*
        * 获取房间消费总额度
        * @param arr $room_ids
        * */
    public function getRoomWealthBuyRoomIds($room_ids,$startDay,$endDay,$search_user_id)
    {
        $where = [];
        if($search_user_id){
            $where['user_id'] = $search_user_id;
        }
        $res = DB::table($this->roomStreamTable)->whereIn('room_id',$room_ids)
            ->where($where)
            ->where('create_timestamp', '>=', strtotime($startDay))
            ->where('create_timestamp', '<=', strtotime($endDay))
            ->groupBy('room_id')
            ->select('room_id', DB::raw('SUM(wealth_value) as diamond_value'))
            ->get();
        return $this->objToArray($res);
    }

    /*
    * 获取房间消费总额
    * @param arr $room_ids
    * @author zxiaofee
    * */
    public function getTotalRoomWealthByRoomIds($un_id)
    {
        $dayStart = strtotime(date('Y-m-d 00:00:00', time()));
        $dayEnd = strtotime(date('Y-m-d 23:59:59', time()));
        $monthStart = strtotime(date('Y-m-01 00:00:00', time()));
        $monthEnd = strtotime(date('Y-m-t 23:59:59', time()));
        $room_ids = "select `room_id` from `zb_union_room` where `un_id` = $un_id";
        $daySql = "select sum(`wealth_value`) as total from `zb_finance_room_wealth_stream` where `room_id` in ($room_ids) and `create_timestamp` >= $dayStart and `create_timestamp` <= $dayEnd";
        $finance_day = DB::select($daySql);
        $finance_day = self::objToArray($finance_day)[0]['total']??0;
        $monthSql = "select sum(`wealth_value`) as total from `zb_finance_room_wealth_stream` where `room_id` in ($room_ids) and `create_timestamp` >= $monthStart and `create_timestamp` <= $monthEnd";
        $finance_month = DB::select($monthSql);
        $finance_month = self::objToArray($finance_month)[0]['total']??0;
        write_log("finance_union", "getTotalRoomWealthByRoomIds", [$finance_day, $finance_month, $daySql, $monthSql]);
        return [$finance_day, $finance_month];
    }

    /*
   * 获取房间消费人数
   * @param arr $room_ids
   * @param $startDay  $endDay起止时间
   * @param $search_user_id 单个用户
   * */
    public function getRoomWealthConsumerUser($room_ids,$startDay,$endDay,$search_user_id)
    {
        $where = [];
        if($search_user_id){
            $where['user_id'] = $search_user_id;
        }
        $res = DB::table($this->roomStreamTable)->whereIn('room_id',$room_ids)
            ->where($where)
            ->where('create_timestamp', '>=', strtotime($startDay))
            ->where('create_timestamp', '<=', strtotime($endDay))
            ->groupBy('user_id')
            ->select('room_id','user_id', DB::raw('SUM(wealth_value) as diamond_value'))
            ->get();
        return $this->objToArray($res);
    }

    /*
     * 获取房间消费用户记录
     * @param arr $room_ids
     * @param $startDay  $endDay起止时间
     * @param $search_user_id 单个用户
     * */
    public function getRoomConsumerUserLog($union_id,$room_id,$startDay,$endDay,$search_user_id,$page,$limit)
    {
        $page--; //入参从1开始

        $s = strtotime($startDay);
        $e = strtotime($endDay);
        $offset = $page * $limit;

        if($room_id > 0){
            $room_sql = "room_id = $room_id";
        }else{
            $room_sql = "room_id in (select room_id from zb_union_room where un_id = $union_id)";
        }

        $sql = "select room_id,user_id,from_user_id,create_timestamp,sum(`wealth_value`) as diamond_value from `zb_finance_room_wealth_stream` where $room_sql and `create_timestamp` BETWEEN $s AND $e GROUP BY room_id,from_user_id ORDER BY diamond_value DESC LIMIT $offset,$limit";
        $res = DB::select($sql);
        return $this->objToArray($res);
    }

    /*
     * 获取房间消费总数
     * @param int $union_id 公会id
     * @param int $room_id 房间id
     * @param $startDay  $endDay起止时间
     * @param $search_user_id 单个用户
     * */
    public function getRoomConsumerTotalValue($union_id,$room_id,$startDay,$endDay)
    {

        $s = strtotime($startDay);
        $e = strtotime($endDay);

        if($room_id > 0){
            $room_sql = "room_id = $room_id";
        }else{
            $room_sql = "room_id in (select room_id from zb_union_room where un_id = $union_id)";
        }

        $sql = "select sum(`wealth_value`) as diamond_value from `zb_finance_room_wealth_stream` where $room_sql AND `create_timestamp` BETWEEN $s AND $e";
        
        $res = DB::select($sql);
        $diamond = $this->objToArray($res)[0]['diamond_value'] ?? 0;
        return intval($diamond);
    }



 /*
 * 获取房间消费用户记录 group by送礼物的用户
 * @param arr $room_ids
 * @param $startDay  $endDay起止时间
 * @param $search_user_id 单个用户
 * */
    public function getRoomConsumerUserLogBySendUser($union_id,$room_id,$startDay,$endDay,$page,$limit)
    {
        $page--; //入参从1开始




        $s = strtotime($startDay);
        $e = strtotime($endDay);
        $offset = $page * $limit;
        if($room_id > 0){
            $room_sql = "room_id = $room_id";
        }else{
            $room_sql = "room_id in (select room_id from zb_union_room where un_id = $union_id)";
        }

        $sql = "select room_id,user_id,from_user_id,create_timestamp,SUM(wealth_value) as diamond_value from `zb_finance_room_wealth_stream` where $room_sql and `create_timestamp` BETWEEN $s AND $e GROUP BY room_id,user_id ORDER BY diamond_value DESC LIMIT $offset,$limit";
        $start_time = microtime(true);
        $res = DB::select($sql);
        $end_time = microtime(true);
        $execution_time = ($end_time - $start_time) * 1000; // Convert to milliseconds
        write_log("getRoomConsumerUserLog", "SQL execution time", ["execution_time" => $execution_time . "ms", "sql" => $sql]);
        return $this->objToArray($res);
    }

    public function getRoomConsumerUserList($room_ids,$startDay,$endDay,$search_user_id)
    {
        $where = [];
        if($search_user_id){
            $where['user_id'] = $search_user_id;
        }
        $res = DB::table($this->roomStreamTable)->whereIn('room_id',$room_ids)
            ->where($where)
            ->where('create_timestamp', '>=', strtotime($startDay))
            ->where('create_timestamp', '<=', strtotime($endDay))
            ->select('room_id','user_id')
            ->groupBy('user_id')
            ->get();
        return $this->objToArray($res);
    }

    /**
     * 房间总流水数据
     * */
    public function getAllWealthTotalToRoomIds($room_ids = []){
        $this->table = 'finance_room_wealth_total';
        $day = '2019-12-05'; //公会等级上线日期开始计算
        $data = DB::table($this->table)
            ->whereIn('room_id',$room_ids)
            ->where('day','>=',$day)
            ->select( DB::raw('SUM(total) as total'))
            ->first();
        return self::objToArray($data);
    }

    /**
     * 按月份查询房间总流水数据  包含预支流水
     * */
    public function getBeforeWealthTotalData($startTime,$endTime){
        $sql = "select a.room_id,sum(a.total) as total, max(user_id) as user_id ,max(total_log) as total_log from zb_finance_room_wealth_total as a
         LEFT JOIN (
            SELECT
            room_id,
            SUM(total) total_log
            FROM
                zb_finance_before_kk_log
                 where `day` between '{$startTime}' and '{$endTime}'
            GROUP BY
                room_id
        ) k_s ON k_s.room_id=a.room_id
         LEFT JOIN zb_room r on r.room_id = a.room_id
                 where `day` between '{$startTime}' and '{$endTime}'
           group by room_id ;";
        $data = DB::select($sql);
        return self::objToArray($data);
    }

    /**获取房主邀请用户的总流水
     * @param int $prvMonth
     * @param $room_id
     * @param $user_ids
     * @return array|mixed
     */
    public function getRoomWealthByUserIds($prvMonth = 0 ,$room_id ,$user_ids)
    {
        $startDay = date('Y-m-01 00:00:00', strtotime("-$prvMonth month"));
        $endDay = date('Y-m-d 23:59:59', strtotime("$startDay +1 month -1 day"));
        $result = DB::table('finance_room_wealth_stream')
            ->where('create_time', '>=', $startDay)
            ->where('create_time', '<=', $endDay)
            ->where('room_id', $room_id)
            ->whereIn('user_id', $user_ids)
            ->select('room_id', DB::raw('sum(wealth_value) as total'))
            ->first();
        if (empty($result)) {
            return [];
        }
        return $this->objToArray($result);
    }

    /**获取房主邀请用户的总流水 审计用 add by zxiaofee
     * @param int $prvMonth
     * @param $room_id
     * @param $user_ids
     * @return array|mixed
     */
    public function getRoomWealthByUserIdsShenji($month ,$room_id ,$user_ids)
    {
        $startDay = date('Y-m-01 00:00:00', strtotime($month));
        $endDay = date('Y-m-d 23:59:59', strtotime("$month +1 month -1 day"));
        $result = DB::table('finance_room_wealth_stream')
            ->where('create_time', '>=', $startDay)
            ->where('create_time', '<=', $endDay)
            ->where('room_id', $room_id)
            ->whereIn('user_id', $user_ids)
            ->select('room_id', DB::raw('sum(wealth_value) as total'))
            ->first();
        if (empty($result)) {
            return [];
        }
        return $this->objToArray($result);
    }

    /**
     * 获取昨日/上周/上个月房间的排行榜
     * @param $type
     * @param $index
     * @param $count
     * @return mixed
     */
    public function get_before_room_charts($type, $index=0, $count=3){
        $str_month = date("Ym",strtotime("-1 month"));
        $str_day = date("Ymd",strtotime("-1 day"));
        $str_week_start = date("Ymd", strtotime('monday last week'));
        $str_week_end   = date("Ymd", strtotime('monday this week - 1 days'));
        $room_day_key = $this->redis_charts_room_wealth_day .  $str_day;
        $room_week_key = $this->redis_charts_room_wealth_week .  $str_week_start . $str_week_end;
        $room_month_key = $this->redis_charts_room_wealth_month .  $str_month;
        $room_all_key = $this->redis_charts_room_wealth_all;


        $key = $room_day_key;

        if ($type == 1){
            $key = $room_day_key;
        }
        if ($type == 2){
            $key = $room_week_key;
        }
        if ($type == 3){
            $key = $room_month_key;
        }
        return Redis::zrevrange($key, $index, $index+$count-1, 'withscores');
    }

    /**
     * 获取昨日/上周/上个月房间的排行榜-最多金
     * @param $type
     * @param $index
     * @param $count
     * @return mixed
     */
    public function get_before_room_charts_maximum_gold($type, $index = 0, $count = 3)
    {
        $str_month = date("Ym",strtotime("-1 month"));
        $str_day = date("Ymd",strtotime("-1 day"));
        $str_week_start = date("Ymd", strtotime('monday last week'));
        $str_week_end   = date("Ymd", strtotime('monday this week - 1 days'));
        $room_day_key = $this->redis_charts_room_wealth_day_maximum_gold .  $str_day;
        $room_week_key = $this->redis_charts_room_wealth_week_maximum_gold .  $str_week_start . $str_week_end;
        $room_month_key = $this->redis_charts_room_wealth_month_maximum_gold .  $str_month;
        $key = $room_day_key;
        if ($type == 1){
            $key = $room_day_key;
        }

        if ($type == 2){
            $key = $room_week_key;
        }

        if ($type == 3){
            $key = $room_month_key;
        }

        return Redis::zrevrange($key, $index, $index + $count - 1, 'withscores');
    }

    //定时同步房间财富值
    public function update_room_charts($wealth_value ,$room_id){
        Redis::HINCRBY($this->redis_cache_finance_room_wealth . date('Ymd', time()), $room_id, $wealth_value);
        Redis::HDEL($this->redis_cache_finance_room_wallet, $room_id);

        $str_month = date("Ym");
        $str_day = date("Ymd");
        $first=1;
        $w=date('w',strtotime($str_day));
        $str_week_start=date('Ymd',strtotime("$str_day -".($w ? $w - $first : 6).' days'));
        $str_week_end=date('Ymd',strtotime("$str_week_start +6 days"));

        $room_user_day_key = $this->redis_charts_room_user_wealth_day . $room_id . $str_day;
        $room_user_week_key = $this->redis_charts_room_user_wealth_week . $room_id . $str_week_start . $str_week_end;
        $room_user_month_key = $this->redis_charts_room_user_wealth_month . $room_id . $str_month;
        $room_user_all_key = $this->redis_charts_room_user_wealth_all . $room_id;

        $users_wealth =  DB::table('finance_room_wealth_stream')
            ->select('user_id',DB::raw('SUM(wealth_value) as total'))
            ->where('room_id', '=', $room_id)
            ->where('create_timestamp', '>=', strtotime(date('Y-m-d')))
            ->where('wealth_type', '!=', 99)
            ->groupBy(['user_id'])
            ->get();

        $users_wealth_count =  DB::table('finance_room_wealth_stream')
            ->select('user_id',DB::raw('count(1) as num'))
            ->where('room_id', '=', $room_id)
            ->where('wealth_type', '=', 99)
            ->where('create_timestamp', '>=', strtotime(date('Y-m-d')))
            ->groupBy(['user_id'])
            ->get();
        $users_wealth = $this->objToArray($users_wealth);
        $users_wealth_count = $this->objToArray($users_wealth_count);

        if ($users_wealth_count){
            $BoardExtendServices= new BoardExtendServices();

            $users_wealth_arr = array_column($users_wealth,'total',  'user_id');
            array_map(function ($val) use ($BoardExtendServices, &$users_wealth_arr) {
                $userId = $val['user_id'];
                $num = $val['num'];
                $todayMaxScore = $BoardExtendServices -> calcTimedGiftScore($num);
                if (array_key_exists($userId, $users_wealth_arr)){
                    $users_wealth_arr[$userId] += $todayMaxScore;
                }else{
                    $users_wealth_arr[$userId] = $todayMaxScore;
                }
            }, $users_wealth_count);

            if ($users_wealth_arr){
                $users_wealth = [];
                foreach ($users_wealth_arr as $key => $value) {
                    $temp = [];
                    $temp['user_id'] = $key;
                    $temp['total'] = $value;
                    $users_wealth[] = $temp;
                }
            }

        }

        write_log('update_room_charts'.(isCli()?'-cli':''), '排行榜修复', ['room_id'=>$room_id,'users_wealth'=>$users_wealth,'users_wealth_count'=>$users_wealth_count]);

        foreach ($users_wealth as $user_wealth){
            $redis_user_wealth = Redis::ZSCORE($room_user_day_key ,$user_wealth['user_id']);
            if($redis_user_wealth != $user_wealth['total']){
                write_log('sync_room_wealth' ,'room_user' ,$room_id.'=='.$user_wealth['user_id']);
                $diff_wealth = $user_wealth['total'] - $redis_user_wealth ;
                Redis::zincrby($room_user_day_key, $diff_wealth, $user_wealth['user_id']);
                Redis::zincrby($room_user_week_key, $diff_wealth, $user_wealth['user_id']);
                Redis::zincrby($room_user_month_key, $diff_wealth, $user_wealth['user_id']);
                //Redis::zincrby($room_user_all_key, $diff_wealth, $user_wealth['user_id']);
            }
        }
        $room_day_key = $this->redis_charts_room_wealth_day .  $str_day;
        $room_week_key = $this->redis_charts_room_wealth_week .  $str_week_start . $str_week_end;
        $room_month_key = $this->redis_charts_room_wealth_month .  $str_month;
        $room_all_key = $this->redis_charts_room_wealth_all;
        Redis::zincrby($room_day_key, $wealth_value, $room_id);
        Redis::zincrby($room_week_key, $wealth_value, $room_id);
        Redis::zincrby($room_month_key, $wealth_value, $room_id);
        Redis::zincrby($room_all_key, $wealth_value, $room_id);
    }

    /**更新房间财富榜单第一名用户-发消息
     * @param $room_id int
     * @param $user_id int 送礼者id
     * @param $to_user_id int 收礼者id
     * @param $inc_value int 本次送礼值
     */
    public function updateRoomChampion($room_id, $user_id, $to_user_id, $inc_value){

        $date = date("Ymd");

        //读取房间当前的神豪和守护uid
        list($vipUser, $mvpUser,$oldLevel) = $this->getRoomVipAndMvpUser($room_id, $date);

        $baseScore = 10000; //超过这个值，才会更新

        //读取送礼者的分数
        $vipKey = $this->redis_charts_room_user_wealth_day . $room_id . $date;
        $myScore = Redis::zscore($vipKey, $user_id);
        $myScore = empty($myScore) ? $inc_value : $myScore + $inc_value;

        //读取送礼者第一名（神豪）
        $vipRes = Redis::zrevrange($vipKey, 0, 0, 'withscores'); //取财富榜单第一名（神豪）
        $vipSend = false;
        $newVipUser = $vipUser;
        if ($vipRes) {
            foreach ($vipRes as $score) {
                if ($myScore > $score && $myScore >= $baseScore) {
                    $vipSend = true;
                    $newVipUser = $user_id;
                    break;
                }
            }
        }elseif($myScore >= $baseScore){
            $vipSend = true;
            $newVipUser = $user_id;
        }

        if (!$vipSend) {
            return;
        }
        //如果我是第一名，读取我的mvp并检查
        //读取收礼者第一名（守护）
        $mvpKey = sprintf($this->redis_charts_room_vip_mvp_charm_day, $room_id, $user_id, $date);

        //读取收礼者的分数
        $toUserScore = Redis::zscore($mvpKey, $to_user_id);
        $toUserScore = empty($toUserScore) ? $inc_value : $toUserScore + $inc_value;
        $mvpSend = false;
        $mvpRes = Redis::zrevrange($mvpKey, 0, 0, 'withscores'); //取财神豪收礼榜第一名

        if ($mvpRes) {
            foreach ($mvpRes as $uid => $score) {
                $newMpvUser = $uid;
                $newMpvScore = $score + $inc_value;
                if ($toUserScore > $score) {
                    $newMpvUser = $to_user_id;
                    $newMpvScore = $toUserScore;
                    $mvpSend = true;
                    break;
                }
            }
        }else{
            $newMpvUser = $to_user_id;
            $newMpvScore = $toUserScore;
            $mvpSend = true;
        }

        //检查等级
        $newLevel = (new FinanceServices())->getRoomChampionLevel($newMpvScore);

        //如果神豪、守护有一个变更，就发送
        if ($vipUser != $newVipUser || $mvpSend || $newLevel > $oldLevel) {
            //更新神豪标记
            $key_user = sprintf($this->redis_charts_room_vip_mvp_user_day, $room_id, $date);
            $val = "$newVipUser,$newMpvUser,$newLevel";
            $set = Redis::setex($key_user, 86400 * 2, $val);
            if ($set == "OK") {
                //发送榜单消息
                (new RoomMsgServices())->roomChampionUpdate($room_id, $newVipUser, $newMpvUser, $toUserScore,$newLevel);
            }
        }
    }

    //
    public function getRoomWealthByRoomId ($roomId, $startTime, $endTime) {
        $wealths = DB::table('finance_room_wealth_stream')
            ->where('room_id', '=', $roomId)
            ->where('create_timestamp', '>=', $startTime)
            ->where('create_timestamp', '<=', $endTime)
            ->select(DB::raw('SUM(wealth_value) as sumValue'))
            ->get();
        return $wealths;
    }

    // 修改排行缓存
    public function updateMonthCache($strMonth, $wealthValue, $roomId) {
        $roomMonthKey = $this->redis_charts_room_wealth_month_maximum_gold . $strMonth;
        $roomMonthKeyY = $this->redis_charts_room_wealth_month .  $strMonth;
        $re = Redis::zincrby($roomMonthKey, $wealthValue, $roomId);
        if (intval($re) <= 0) {
            Redis::zrem($roomMonthKey, $roomId);
        }
        $reY = Redis::zincrby($roomMonthKeyY, 0-$wealthValue, $roomId);
        if (intval($reY) <= 0) {
            Redis::zrem($roomMonthKeyY, $roomId);
        }
    }

    // 修改排行缓存
    public function updateWeekCache($strWeekStart, $strWeekEnd, $wealthValue, $roomId) {
        $roomWeekKey = $this->redis_charts_room_wealth_week_maximum_gold . $strWeekStart . $strWeekEnd;
        $roomWeekKeyY = $this->redis_charts_room_wealth_week .  $strWeekStart . $strWeekEnd;
        $re = Redis::zincrby($roomWeekKey, $wealthValue, $roomId);
        if (intval($re) <= 0) {
            Redis::zrem($roomWeekKey, $roomId);
        }
        $reY = Redis::zincrby($roomWeekKeyY, 0-$wealthValue, $roomId);
        if (intval($reY) <= 0) {
            Redis::zrem($roomWeekKeyY, $roomId);
        }
    }

    // 修改排行缓存
    public function updateDayCache($strDay, $wealthValue, $roomId) {
        $userDayKey = $this->redis_charts_room_wealth_day_maximum_gold .  $strDay;
        $userDayKeyY = $this->redis_charts_room_wealth_day . $strDay;
        $re = Redis::zincrby($userDayKey, $wealthValue, $roomId);
        if (intval($re) <= 0) {
            Redis::zrem($userDayKey, $roomId);
        }
        $reY = Redis::zincrby($userDayKeyY, 0-$wealthValue, $roomId);
        if (intval($reY) <= 0) {
            Redis::zrem($userDayKeyY, $roomId);
        }
    }

    // 修改排行缓存
    public function updateAllCache($wealthValue, $roomId) {
        $userAllKey = $this->redis_charts_room_wealth_all_maximum_gold;
        $userAllKeyY = $this->redis_charts_room_wealth_all;
        Redis::zincrby($userAllKey, $wealthValue, $roomId);
        Redis::zincrby($userAllKeyY, 0-$wealthValue, $roomId);
    }
    /**
     * 修复最多金房间月榜缓存
     */
    public function updateRoomMonthChartsCache ($maximumGoldRoomIds, $strMonth, $startTime, $endTime) {
        if ($maximumGoldRoomIds) {// 最多金榜单

            $strDay = date("Ymd");
            $first = 1;
            $w = date('w',strtotime($strDay));
            $strWeekStart = date('Ymd',strtotime("$strDay -".($w ? $w - $first : 6).' days'));
            $strWeekEnd = date('Ymd',strtotime("$strWeekStart +6 days"));
            $roomWeekKey = $this->redis_charts_room_wealth_week_maximum_gold . $strWeekStart . $strWeekEnd;
            $roomMonthKey = $this->redis_charts_room_wealth_month_maximum_gold .  $strMonth;
            $roomAllKey = $this->redis_charts_room_wealth_all_maximum_gold;

            foreach ($maximumGoldRoomIds as $k => $v) {
                $roomId = (int)$v;
                Log::info ('修复最多金房间月榜缓存:updateRoomMonthChartsCache:房间号:' . $roomId);
                if ($roomId <= 0) {
                    continue;
                }

                $wealthValue = DB::table('finance_room_wealth_stream')
                    ->where('room_id', '=', $roomId)
                    ->where('create_time', '>=', $startTime)
                    ->where('create_time', '<=', $endTime)
                    ->select('id', 'room_id', 'user_id', 'wealth_value', 'create_time')
                    ->orderBy('id','asc')
                    ->get();

                if (count($wealthValue) <= 0) {
                    Log::info('修复最多金房间月榜缓存:updateRoomMonthChartsCache:房间号:' . $roomId . '没有流水');
                    continue;
                }

                foreach ($wealthValue as $k=>$v) {
                    Log::info('修复最多金房间月榜缓存:updateRoomMonthChartsCache:ID:' . $v->id);
                    Redis::zincrby($roomMonthKey, $v->wealthValue, $roomId);
                    Redis::zincrby($roomAllKey, $v->wealthValue, $roomId);
                    if (strtotime($strWeekStart . '00:00:00') >= strtotime($v->create_time)) {
                        Redis::zincrby($roomWeekKey, $v->wealth_value, $v->room_id);
                        $roomWeekKeyY = $this->redis_charts_room_wealth_week .  $strWeekStart . $strWeekEnd;
                        Redis::zincrby($roomWeekKeyY, 0-($v->wealth_value), $v->room_id);
                    }
                    $roomMonthKeyY = $this->redis_charts_room_wealth_month .  $strMonth;
                    $roomAllKeyY = $this->redis_charts_room_wealth_all;
                    Redis::zincrby($roomMonthKeyY, 0-($v->wealth_value), $roomId);
                    Redis::zincrby($roomAllKeyY, 0-($v->wealth_value), $roomId);
                }
            }
        }
    }

    //获取本周房间财富榜
    public function checkRoomWealthUserWeek($room_user_week_key,$room_id , $str_week_start , $str_week_end){
        if(!Redis::EXISTS($room_user_week_key) && date('w') != 1){
            if ($this->redis_lock($room_user_week_key,5)){
                $str_week_start = date('Y-m-d 00:00:00',strtotime($str_week_start));
                $str_week_end = date('Y-m-d 23:59:59',strtotime($str_week_end));
                $data = $this->getRoomWealthBroad($room_id,$str_week_start,$str_week_end);
                foreach ($data as $value){
                    Redis::zincrby($room_user_week_key, $value['wealth_total'], $value['user_id']);
                }
                if(Redis::TTL($room_user_week_key) == -1){
                    Redis::EXPIRE($room_user_week_key, 2 * 7 * 24 * 3600);
                }
            }
        }
        return true;
    }

    public function getRoomWealthBroad($room_id,$str_start,$str_end){
        $data = DB::table($this->roomStreamTable)
            ->whereBetween('create_time',[$str_start,$str_end])
            ->where('room_id',$room_id)
            ->groupBy('user_id')
            ->select('user_id', DB::raw('sum(wealth_value) as wealth_total'))
            ->get();
        return $this->objToArray($data);
    }


    /**
     * Redis 锁 type 1:手动解锁 2：超时解锁
     * @param $key
     * @param int $lockExpire
     * @return bool
     */
    function redis_lock($key, $lockExpire = 3)
    {
        $lockKey = 'lock:' . $key;

        $lockValue = time() + $lockExpire;

        $ret = Redis::setnx($lockKey, $lockValue);
        if (!$ret) {
            return false;
        }
        Redis::expire($lockKey, $lockExpire);
        return true;

    }


    /**
     * 读取当前房间的神豪和守护用户id
     * @param $room_id int
     * @param $date string 时间
     * @return array
     */
    public function getRoomVipAndMvpUser($room_id, $date){
        $key_user = sprintf($this->redis_charts_room_vip_mvp_user_day, $room_id, $date);
        $vip_mvp = Redis::get($key_user);
        $vip_user = $mvp_user = $level = 0;
        if (!empty($vip_mvp)) {
            list($vip_user, $mvp_user, $level) = explode(",", $vip_mvp);
        }
        return [$vip_user, $mvp_user, $level];
    }

}
